<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <el-button size="default" type="primary" @click="NewData">新建</el-button>
        <el-button size="default" type="danger" @click="DeleteData">删除</el-button>
        <el-button size="default" type="success" @click="Re">刷新</el-button>
        <el-input size="default" class="left-10 right-10" style="width: 200px;" v-model="fuzzyquery"></el-input>
        <el-button size="default" type="primary" plain>模糊查询</el-button>
        <el-button size="default" type="primary" plain>使用记录</el-button>
        <el-button size="default" type="primary" @click="SaveData" plain>保存</el-button>
      </el-header>
      <el-main>
        <el-row>
          <el-col :span="6">
            <vxe-table
                border
                size="mini"
                show-header-overflow
                show-overflow
                ref="DataGridList"
                :column-config="{ resizable: true }"
                :row-config="{ isCurrent: true, isHover: true }"
                @current-change="DataGridChangeEvent"
                :data="datagridList">
              <vxe-column field="dataGridName" title="列表名称"></vxe-column>
            </vxe-table>
          </el-col>
          <el-col :span="18">
            <vxe-form style="padding: 0 10px !important;" :data="formData" size="mini">
              <vxe-form-gather span="12" style="padding:0 10px !important;">
                <vxe-form-item field="dataGridName" title="列表名称" :span="12"
                               :item-render="{name:'input'}"></vxe-form-item>
                <vxe-form-item field="windowWidth" title="窗体宽度" :span="12"
                               :item-render="{name:'input'}"></vxe-form-item>
                <vxe-form-item field="windowHeight" title="窗体高度" :span="12"
                               :item-render="{name:'input'}"></vxe-form-item>
                <vxe-form-item field="newTemplate" title="新建模版" :span="12"
                               :item-render="{name:'input'}"></vxe-form-item>
              </vxe-form-gather>
              <vxe-form-gather span="12">
                <vxe-form-item title="备注" :span="24" field="memo"
                               :item-render="{name:'$textarea',resize:true,props:{ autosize:{minRows: 3, maxRows: 3}}}"></vxe-form-item>
              </vxe-form-gather>

              <vxe-form-gather span="24">
                <vxe-form-item field="windowHeight" title="每页显示的记录数">
                 <template #default="{ data }">
                   <vxe-input type="number" v-model="data.topNumber"></vxe-input>
                </template>

                </vxe-form-item>
                <vxe-form-item title="自动检索">
                  <vxe-checkbox></vxe-checkbox>
                </vxe-form-item>
                <vxe-form-item title="排除重复">
                  <vxe-checkbox></vxe-checkbox>
                </vxe-form-item>
                <vxe-form-item title="返回结果到单行(列)">
                  <vxe-checkbox></vxe-checkbox>
                </vxe-form-item>
                <vxe-form-item title="选择外部表">
                  <vxe-input v-model="formData.allowOdata"></vxe-input>
                </vxe-form-item>
                <vxe-form-item title="允许检索隐藏列">
                  <vxe-checkbox></vxe-checkbox>
                </vxe-form-item>
                <vxe-form-item title="输入条件后显示结果">
                  <vxe-checkbox></vxe-checkbox>
                </vxe-form-item>

              </vxe-form-gather>
            </vxe-form>
            <el-tabs type="border-card">
              <el-tab-pane label="数据源">
                <el-row>
                  <el-col :span="6" class="bor">
                    <vxe-table
                        show-overflow
                        ref="xTree"
                        size="mini"
                        :show-header="false"
                        height="250px"
                        :tree-config="{}"
                        keep-source
                        @cell-dblclick="TableChangeEventAdd"
                        :row-config="{isCurrent: true, isHover: true}"
                        :data="sourceTableData">
                      <vxe-column field="title" tree-node @dblclick="setSelectTable"></vxe-column>
                    </vxe-table>
                    <vxe-input sapn="24" placeholder="可清除" size="mini" type="search" clearable></vxe-input>
                    <p class="prompt">已选择数据表</p>
                    <vxe-table
                        show-overflow
                        ref="selectTables"
                        size="mini"
                        keep-source
                        height="150px"
                        :show-header="false"
                        @cell-dblclick="TableChangeEventDelete"
                        :row-config="{isCurrent: true, isHover: true}"
                        :data="selectTablesData">
                      <vxe-column field="tableDispName"></vxe-column>
                    </vxe-table>
                  </el-col>
                  <el-col class="bor" :span="18">
                    <div class="viewbuton">
                      <span>筛选条件：</span>
                      <el-button type="primary" size="default" @click="showchose2">条件表达式</el-button>
                    </div>
                    <el-input
                        type="textarea"
                        :rows="8"
                        placeholder="请输入内容"
                        v-model="formData.filterExpr">
                    </el-input>
                    <div class="viewbuton">
                      <span>表间关系：</span>
                      <el-button type="primary" size="default" @click="newRlations">新建表间关联</el-button>
                    </div>
                    <vxe-table
                        show-overflow
                        ref="selectRelations"
                        size="mini"
                        keep-source
                        :tree-config="{}"
                        height="194px"
                        :row-config="{isCurrent: true, isHover: true}"
                        :data="relationsData"
                        :edit-config="{trigger: 'click', mode: 'cell', icon: 'fa fa-pencil', showStatus: true}">
                      <vxe-column field="tableDispName1" title="表1"
                                  :edit-render="{name:'$select',options:selectTablesDataOptions,events:{change:rtchange}}"></vxe-column>
                      <vxe-column field="relationType" title="关联"
                                  :edit-render="{name:'$select',options:[{label:'LEFT JOIN',value:'Left Join'},{label:'RIGHT JOIN',value:'RIGHT JOIN'},{label:'INNER JOIN',value:'INNER JOIN'},]}"></vxe-column>
                      <vxe-column field="tableDispName2" title="表2"
                                  :edit-render="{name:'$select',options:selectTablesDataOptions,events:{change:rtchange}}"></vxe-column>
                      <vxe-column field="relationExpr" title="关联条件"
                                  :edit-render="{name:'$input',events:{click:showchose}}"></vxe-column>
                    </vxe-table>
                  </el-col>
                </el-row>
              </el-tab-pane>
              <el-tab-pane label="列表字段">
                <el-alert style="width: 100%;" title="提示：双击左侧树节点可以快速设置[提取项]" type="warning" :closable="false"/>
                <div class="top-10"></div>
                <el-row>
                  <el-col :span="4">
                    <vxe-table
                        show-overflow
                        ref="sourceField"
                        size="mini"
                        keep-source
                        height="250px"
                        :show-header="false"
                        :tree-config="{}"
                        :row-config="{isCurrent: true, isHover: true}"
                        @cell-dblclick="fieldChangeEventAdd"
                        :data="sourceFieldData">
                      <vxe-column field="title" tree-node></vxe-column>
                    </vxe-table>
                  </el-col>
                  <el-col :span="20">
                    <vxe-table
                        border
                        :column-config="{resizable: true}"
                        ref="selectFields"
                        size="mini"
                        height="100%"
                        keep-source
                        :row-config="{isCurrent: true, isHover: true}"
                        :edit-config="{trigger: 'click', mode: 'cell', icon: 'fa fa-pencil', showStatus: true}"
                        :data="fieldSelectData">
                      <vxe-column field="fieldExpr" title="提取项" width="250"></vxe-column>
                      <vxe-column field="fieldDispName" title="提取项别名" width="120"
                                  :edit-render="{name:'input'}"></vxe-column>
                      <vxe-column field="dispSeq" title="顺序" width="80" :edit-render="{name:'input'}"
                                  align="center"></vxe-column>
                      <vxe-column field="orderbyPri" title="排序" width="80" :edit-render="{}" align="center">
                        <template #edit="{ row }">
                          <vxe-select v-model="row.orderbyPri" transfer>
                            <vxe-option :value="0" label="无"></vxe-option>
                            <vxe-option :value="1" label="顺序"></vxe-option>
                            <vxe-option :value="2" label="倒序"></vxe-option>
                          </vxe-select>
                        </template>
                          <template #default="{ row }">
                            <vxe-select v-model="row.orderbyPri" transfer>
                              <vxe-option :value="0" label="无"></vxe-option>
                              <vxe-option :value="1" label="顺序"></vxe-option>
                              <vxe-option :value="2" label="倒序"></vxe-option>
                            </vxe-select>
                        </template>
                      </vxe-column>
                      <vxe-column field="allowFixedWidth" title="宽度" width="80"
                                  :edit-render="{name:'input',props:{type:'integer'}}" align="center"></vxe-column>
                      <vxe-column field="hidden" title="隐藏" width="60" align="center">
                        <template #default="{ row }">
                          <vxe-checkbox v-model="row.hidden" :checked-value=1 :unchecked-value=0></vxe-checkbox>
                        </template>
                      </vxe-column>
                      <vxe-column field="allowLikeSearch" title="查询类型" width="100" :cell-render="{name: '$select', options:searchType}"></vxe-column>
                      <vxe-column field="hidden" title="操作" width="100">
                        <template #default="{ row}">
                          <vxe-button @click="$refs.selectFields.remove(row)">删除</vxe-button>
                        </template>
                      </vxe-column>
                    </vxe-table>
                  </el-col>
                </el-row>
                <el-tabs class="top-10" type="border-card">
                  <el-tab-pane label="列表自动分类">列表自动分类</el-tab-pane>
                  <el-tab-pane label="构建分类树">构建分类树</el-tab-pane>
                  <el-tab-pane label="组合树形规范">组合树形规范</el-tab-pane>
                </el-tabs>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
    <filterchooseone v-show="Schoose" ref="filters" :LData="sourceFieldData" @submitt="Schooseshow"></filterchooseone>
  </div>
</template>

<script>
import {onBeforeMount, reactive, ref, toRefs} from "vue-demi"
import XEUtils from 'xe-utils'
import {getDataGridSource, GetTables, listDatagrid, updateDatagrid, delDatagrid} from '/@/api/linkoo/datagrid'
import {ElMessage} from 'element-plus'
import Filterchooseone from '../../../components/template/filterchooseone.vue'

export default {
  components: {Filterchooseone},
  setup(props) {
    let state = reactive({
      datagridList: [],
      queryParams: {pageNum:1,pageSize:1000},
      sourceTableData: [],
      formData: {dataGridID: 0},
      selectTablesData: [],
      fieldSelectData: [],
      selectTablesDataOptions: [],
      sourceFieldData: [],
      FieldData: [],
      searchType:[{value: 0, label: '不查询'}, {value: 1,operate:'like', label: '快搜'}, {value:2,operate: '=', label: '等于'}, {value: 3,operate:'<>', label: '不等于'},
        {value: 4,operate:'<',label: '小于'}, {value:5,operate: '<=', label: '小于等于'}, {value:6,operate: '>', label: '大于'}, {value: 7,operate:'>=', label: '大于等于'},
       {value: 8,operate:'in', label: '在列表中'}, {value: 9,operate:'between', label: '区间'}],
      selectFilterTarget: {},
      relationsData: []
    })
    let fuzzyquery = ref('')
    let selectFilterTargetField = ref('')
    let loading = ref('')
    let Schoose = ref(false)
    const selectTables = ref(null)
    const filters = ref(null)
    const selectRelations = ref(null)
    const selectFields = ref(null)
    const DataGridList = ref(null)
    onBeforeMount(() => {
      getList();
    })
    const DataGridChangeEvent = ({row}) => {
      state.formData = row
      state.selectTablesData = []
      state.fieldSelectData = []
      getDataGridSource(row.dataGridID).then(res => {
        state.selectTablesData = res.data.table
        state.fieldSelectData = res.data.field
        state.relationsData = res.data.relations
        setTimeout(() => {
          getSTF()
        }, 20)
      })
    }
    const getSTF = () => {
      let dd = XEUtils.map(selectTables.value.getTableData().fullData, item => item.ruleType + item.tableName)
      state.selectTablesDataOptions = selectTables.value.getTableData().fullData.map((item, index) => {
        return {label: item.tableDispName, value: item.tableName, tableID: item.tableID}
      })
      state.sourceFieldData = XEUtils.filter(state.FieldData, item => XEUtils.includes(dd, item.BJ))
    }
    const getList = () => {
      listDatagrid(state.queryParams).then((res) => {
        console.log();
        if (res.code === 0) {
          state.datagridList = XEUtils.toArray(res.data.list)
          loading.value = false
          getTF()
        }
      })
    }
    const NewData = () => {
      state.formData = {dataGridID: 0}
      state.selectTablesData = []
    }
    const DeleteData = () => {
      const data = DataGridList.value.getCurrentRecord()
      console.log(data.dataGridID)
      delDatagrid([data.dataGridID]).then((res) => {
        if (res.code === 0) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        }
        getList()
      })

    }
    const getTF = () => {
      GetTables().then(res => {
        let d = [], tb = {}
        let tempobj = {}, tempview = [], tempodb = {}
        res.data.table.forEach(row => {
          if (row.category === 2) {
            tempview.push(Object.assign({title: row['TemplateName'], ist: true}, row))
          } else if (row.category === 1) {
            if (tempobj[row.category + row['TemplateID'] + row['TemplateName']] === undefined) {
              tempobj[row.category + row['TemplateID'] + row['TemplateName']] = {
                title: row['TemplateName'],
                ist: false,
                children: []
              }
            }
            tempobj[row.category + row['TemplateID'] + row['TemplateName']].children.push(Object.assign({
              title: row['TableDispName'],
              ist: true
            }, row))
            tempobj[row.category + row['TemplateID'] + row['TemplateName']].children = XEUtils.orderBy(tempobj[row.category + row['TemplateID'] + row['TemplateName']].children, [['TableID', 'asc']])
          } else if (row.category === 3) {
            if (tempodb[row.category + row['TemplateID'] + row['TemplateName']] === undefined) {
              tempodb[row.category + row['TemplateID'] + row['TemplateName']] = {
                title: row['TemplateName'],
                ist: false,
                children: []
              }
            }
            tempodb[row.category + row['TemplateID'] + row['TemplateName']].children.push(Object.assign({
              title: row['TableDispName'],
              ist: true,
              od: row['TemplateName']
            }, row))
            tempodb[row.category + row['TemplateID'] + row['TemplateName']].children = XEUtils.orderBy(tempodb[row.category + row['TemplateID'] + row['TemplateName']].children, [['TableID', 'asc']])
          }
        })
        res.data.field.forEach(row => {
          if (tb[row.category + row['TableName']] === undefined) {
            tb[row.category + row['TableName']] = {
              'BJ': row['category'] + row['TableName'],
              ist: false,
              'TableName': row['TableName'],
              'title': '[' + row['TableDispName'] + ']',
              children: []
            }
          }
          tb[row.category + row['TableName']].children.push(Object.assign({
            title: '[' + row['FieldDispName'] + ']',
            ist: true
          }, row))
        })

        d.push({title: '模板', children: XEUtils.toArray(tempobj)})
        d.push({title: '视图', children: tempview})
        d.push({title: '外部表', children: XEUtils.toArray(tempodb)})
        state.sourceTableData = XEUtils.toArray(d)
        state.FieldData = XEUtils.toArray(tb)
      })
    }
    const setSelectTable = (data) => {
      console.log(data)
    }
    const TableChangeEventAdd = ({row}) => {
      console.log(row);
      if (row.ist) {
        if (XEUtils.filter(selectTables.value.getTableData().fullData, item => (item.tableName === row.TableName && item.ruleType === row.category)).length > 0) {
          ElMessage({
            type: 'error',
            message: row.TableDispName + ' 已经选择,请不要重复选择',
          })
          return
        }
        if (XEUtils.filter(selectTables.value.getTableData().fullData, item => ((row.category === 3 && item.ruleType < row.category) || (row.category < 3 && item.ruleType === 3))).length > 0) {
          ElMessage({
            type: 'error',
            message: "外部表和内部表不能同时使用!",
          })
          return
        }
        if (XEUtils.toValueString(state.formData.allowOdata) !== '' && state.formData.allowOdata !== XEUtils.toValueString(row.od)) {
          ElMessage({
            type: 'error',
            message: '不同外部数据库不能同时使用!',
          })
          return
        }
        state.formData.allowOdata = XEUtils.toValueString(row.od)
        let record = {
          "sourceID": 0,
          "ruleID": state.formData.dataGridID,
          "tableID": row.TableID,
          "tableDispName": row.TableDispName,
          "tableName": row.TableName,
          "ruleType": row.category
        }
        selectTables.value.insertAt(record, -1)
        getSTF()
      }
    }
    const TableChangeEventDelete = ({row}) => {
      selectTables.value.remove(row)
      getSTF()
    }
    const showchose2 = () => {
      state.selectFilterTarget = state.formData
      selectFilterTargetField.value = 'filterExpr'
      filters.value.filterText = XEUtils.toValueString(state.formData.filterExpr)
      Schoose.value = true
    }
    const newRlations = () => {
      let record = {
        "sourceRelationID": 0,
        "ruleID": state.formData.dataGridID,
        "tableID1": null,
        "tableName1": null,
        "tableDispName1": null,
        "relationType": "LEFT JOIN",
        "tableID2": null,
        "tableName2": null,
        "tableDispName2": null,
        "relationExpr": null,
        "ruleType": null
      }
      const $table = selectRelations.value
      const {row: newRow} = $table.insertAt(record, -1)
      $table.setActiveCell(newRow, 'tableDispName1')
    }
    const fieldChangeEventAdd = ({row}) => {
      if (row.ist) {
        let record = {
          "dataGridFieldID": 0,
          "dataGridID": state.formData.dataGridID,
          "hidden": 0,
          "allowLikeSearch": 0,
          "allowMobile": 0,
          "fieldExpr": row.FieldExpr,
          "fieldDispName": row.FieldDispName,
          "orderBy": "",
          "dispSeq": 0,
          "orderbyPri": 0,
          "defaultReturn": 0,
          "allowFastSum": 0,
          "allowFastUniqueCount": 0,
          "allowImage": 0,
          "allowFixedWidth": 100
        }
        selectFields.value.insertAt(record, -1)
        console.log(row)
      }
    }
    const Schooseshow = ({filterText, update}) => {
      if (update) {
        state.selectFilterTarget[state.selectFilterTargetField] = filterText
        state.formData.filterExpr = filterText
        console.log(state.selectFilterTarget[state.selectFilterTargetField], "2345678");
      }
      Schoose.value = false
    }
    const rtchange = (row,column) => {
      console.log(row,column)
      const data = XEUtils.find(state.selectTablesDataOptions, item => item.value === row[column.property])
      if (!data) {
        return
      }
      if (column.property === 'tableDispName1') {
        row.tableName1 = data.value
        row.tableDispName1 = data.label
        row.tableID1 = data.tableID
      } else {
        row.tableName2 = data.value
        row.tableDispName2 = data.label
        row.tableID2 = data.tableID
      }
    }
    const showchose = ({row}) => {
      state.selectFilterTarget = row
      state.selectFilterTargetField = 'relationExpr'
      filters.value.filterText = XEUtils.toValueString(row.relationExpr)
      Schoose.value = true
    }
    const SaveData = () => {
      let Data = {}
      Data['M'] = state.formData
      Data['T'] = selectTables.value.getTableData().fullData.map((row, index) => {
        delete row['_X_ID'];
        return row
      })
      Data['M'].fromExpr = '[' + Data['T'][0].tableDispName + ']'
      Data['R'] = selectRelations.value.getTableData().fullData.map((row, index) => {
        delete row['_X_ID'];
        return row
      })
      let i=0
      Data['F'] = selectFields.value.getTableData().fullData.map((row, index) => {
        delete row['_X_ID'];
        row.allowFixedWidth = XEUtils.toNumber(row.allowFixedWidth);
        row.hidden = XEUtils.toNumber(row.hidden);
        row.dispSeq = XEUtils.toNumber(row.dispSeq);
        i+=row.orderbyPri
        return row
      })
      if (i<1&&state.formData.allowOdata!==''){
        ElMessage.warning("使用了外部表,请设置一个字段排序!")
        return
      }
      updateDatagrid(Data, state.formData.dataGridID).then(response => {
        if (response.code === 0) {
          ElMessage({
            type: 'success',
            message: '修改成功',
          })
        } else {
          ElMessage({
            type: 'error',
            message: response.msg,
          })
        }
      })
    }
    return {
      fuzzyquery,
      ...toRefs(state),
      DataGridChangeEvent,
      loading,
      NewData,
      getTF,
      getSTF,
      selectTables,
      filters,
      selectFields,
      DataGridList,
      DeleteData,
      setSelectTable,
      TableChangeEventAdd,
      TableChangeEventDelete,
      showchose2,
      showchose,
      Schoose,
      newRlations,
      selectRelations,
      fieldChangeEventAdd,
      Schooseshow,
      rtchange,
      SaveData
    }
  }
}
</script>

<style scoped>
.left-10 {
  margin-left: 10px;
}

.right-10 {
  margin-right: 10px;
}

.top-10 {
  margin-top: 10px;
}

.el-header {
  padding: 0;
  height: 40px;
}

.el-main {
  border: 1px solid #d2d2d2;
  border-radius: 5px;
  height: 100vh;
  padding: 0;
}

.prompt {
  color: rgba(0, 0, 0, 0.451);
  padding: 5px;
}

.bor {
  border: 1px solid #d2d2d2;
}

.viewbuton {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 5px;
  border-bottom: 1px solid #d2d2d2;
}
</style>